
const BASE_URL = 'https://api.www.fngyzb.com/'


const slides = document.getElementsByClassName('swiper-slide')
const bullets = document.getElementsByClassName('swiper-pagination-bullet')
const nums = document.getElementsByClassName('num')
let num = 0
let autoplay = null

const handleChangeSwiper = (v) => {
  clearInterval(autoplay)
  num = v
  for(let i = 0; i < bullets.length; i++) {
    if(v === i) {
      bullets[i].classList.add('active')
      slides[i].classList.add('active')
    } else{
      bullets[i].classList.remove('active')
      slides[i].classList.remove('active')
    }
  }
  autoSwiper()
}



const autoSwiper = () => {
  autoplay = setInterval(() => {
    num++
    if(num > slides.length - 1) {
      num = 0
    }
    handleChangeSwiper(num)
  }, 5000)
}

if(slides) {
  autoSwiper()
}

// 这里是用于移动端菜单的JavaScript代码
function toggleMenu() {
  const menu = document.getElementById('nav-menu');
  if (menu.style.display === 'none' || menu.style.display === '') {
    menu.style.display = 'block';
  } else {
    menu.style.display = 'none';
  }
}

let lastScrollTop = 0;

window.addEventListener('scroll', function() {
  const header = document.getElementById('main-header');
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;

  if (scrollTop > lastScrollTop) {
    // 向下滚动
    header.classList.add('hidden');
    handleOut()
  } else {
    // 向上滚动
    header.classList.remove('hidden');
  }

  lastScrollTop = scrollTop <= 0 ? 0 : scrollTop;
});
const startRolling = (el, targetNumber, duration) => {
  let startTime = null;
  const step = (timestamp) => {
    if (!startTime) startTime = timestamp;
    const progress = timestamp - startTime;
    const easeInOutExpo = (t, b, c, d) => {
      t /= d / 2;
      if (t < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
      t--;
      return c / 2 * (-Math.pow(2, -10 * t) + 2) + b;
    };
    const currentNumber = easeInOutExpo(progress, 0, targetNumber, duration);
    el.textContent = Math.floor(currentNumber).toString();

    if (progress < duration) {
      requestAnimationFrame(step);
    } else {
      el.textContent = targetNumber.toString();
    }
  };

  requestAnimationFrame(step);
};

if(nums.length > 0) {
  // 调用函数，设置目标数字和动画持续时间
  startRolling(nums[0], 5, 2000);  // 滚动到12345，耗时2秒
  startRolling(nums[1], 10, 2000);  // 滚动到12345，耗时2秒
  startRolling(nums[2], 4, 2000);  // 滚动到12345，耗时2秒
}


const headerDate = [
  {
    name: '公司简介',
    path: 'about.html#about',
    pid: 0,
  },
  // {
  //   name: '企业发展',
  //   path: '#',
  //   pid: 0,
  // },
  {
    name: '企业文化',
    path: 'about.html#business',
    pid: 0,
  },
  // {
  //   name: '组织架构',
  //   path: 'about.html#organization',
  //   pid: 0,
  // },
  {
    name: '田蓬口岸',
    path: 'business.html#bus1',
    pid: 1,
  },
  {
    name: '体育板块',
    path: 'business.html#bus2',
    pid: 1,
  },
  {
    name: '城市服务',
    path: 'business.html#bus3',
    pid: 1,
  },
  {
    name: '农林板块',
    path: 'business.html#bus4',
    pid: 1,
  },
  {
    name: '旅游板块',
    path: 'business.html#bus5',
    pid: 1,
  },
  {
    name: '医疗板块',
    path: 'business.html#bus6',
    pid: 1,
  },
  {
    name: '文化传媒',
    path: 'business.html#bus7',
    pid: 1,
  },
  {
    name: '供应链',
    path: 'business.html#bus8',
    pid: 1,
  },
  {
    name: '殡葬板块',
    path: 'business.html#bus9',
    pid: 1,
  },
  {
    name: '合作伙伴',
    path: 'cooperation.html#cooperation',
    pid: 3,
  },
  {
    name: '合作申请',
    path: 'cooperation.html#application',
    pid: 3,
  },
  // {
  //   name: '给我们留言',
  //   path: '#',
  //   pid: 4,
  // },
  // {
  //   name: '联系方式',
  //   path: '#',
  //   pid: 4,
  // },
]
const menu = document.querySelector('.header-menu')

const handleHover = (v) => {
  menu.style.zIndex = '1000'
  menu.style.display = 'block'
  const item = headerDate.filter((item) => item.pid === v)
  let html = ''
  if(item.length == 0) {
    menu.style.display = 'none'
  } else {
    menu.style.display = 'block'
  }
  item.forEach((e) => {
    html = html + `<span class="header-li"><a href="${e.path}">${e.name}</a></span>`
  })
   document.querySelector('#header-menu').innerHTML = (html)
}

const handleOut = () => {
  menu.style.zIndex = '-1'
  menu.style.display = 'none'
}

const handleEnter = () => {
  menu.style.zIndex = '1000'
  menu.style.display = 'block'
}


function getNewsList () {
  fetch(BASE_URL + 'news', { // 这里替换为实际的API地址
      method: 'GET',
      headers: {
          'Content-Type': 'application/json'
      }
  })
  .then(response => response.json())
  .then(data => {
    const { code, msg, data: newsList } = data; // 假设返回的数据结构为 { code, msg, data: newsList }
    if (code === 200) {
      newsList.forEach((item, index) => {
        item.id = index + 1
        return item
      })
      const news_data = newsList

      news_data.slice(0, 3).forEach((item, index) => {
        const year = new Date(item.updateTime).getFullYear();
        const month = new Date(item.updateTime).getMonth() + 1;
        const day = new Date(item.updateTime).getDate();
        console.log(item.desc)
        // if(location.href.includes('new.html')) {
        //   item.desc
        // }
        item.desc = item.desc.replace(/<[^>]+>/g, '')
        const newsHtml = `
        <div class="news-content">
                  <div class="flex bdr width-full">
                    <div class="news width-full">
                      <a class="news-title flex btw"href="${location.origin + '/new.html'}?id=${item._id}">
                        <b class="ellipsis p-2 ">${item.title_cn}</b>
                        <span>${year}/${month}/${day}</span>
                      </a>
                      <span class="news-article">${item.desc}</span>
                    </div>
                  </div>
                </div>
        `
        news.innerHTML += newsHtml;
      })

      news_data.slice(3,7).forEach((item) => {
        const year = new Date(item.updateTime).getFullYear();
        const month = new Date(item.updateTime).getMonth() + 1;
        const day = new Date(item.updateTime).getDate();
        const newsHtml = `
            <div class="news-content">
              <div class="flex bdr"><div>
                <p class="time">${year}</p>
                <span class="year">${month}/${day}</span>
              </div>
              <div class="news">
                 <a class="news-title flex btw"href="${location.href.replace('news.html', 'new.html')}?id=${item._id}">
                 <b >${item.title_cn}</b>
                  <span>${year}/${month}/${day}</span>
                 </a>
                    <span class="news-article">${item.desc}</span>
              </div></div>
            </div>
          `
          if(newsOther) {
            newsOther.innerHTML += newsHtml;
          }
      })
    } else {
      console.error('Error:', msg);

    }
  })
}
const news = document.getElementById('news');
const newsOther = document.getElementById('news-other');
if( news) {
  getNewsList()
}

// if(location.href.includes('index')) {
//   getNewsList()
// }






function textToHtmlParagraphs(text) {
  // console.log(text)
  // 分割文本
  let paragraphs = text.split('。');
  // 过滤掉可能存在的空字符串
  paragraphs = paragraphs.filter(paragraph => paragraph.trim().length > 0);
  // 添加<p>标签
  let htmlParagraphs = paragraphs.map(paragraph => `<p>${paragraph}。</p>`);
  // 返回组合后的HTML字符串
  return htmlParagraphs.join('');
}


const newsDetail = document.getElementById('news-detail');



if(newsDetail) {
  const urlParams = new URLSearchParams(window.location.search);
  const id = urlParams.get('id');
  fetch(BASE_URL + 'news', { // 这里替换为实际的API地址
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
    },
    data: {
      _id: id
    }
})
.then(response => response.json())
.then(data => {
  const { code, msg, data: news_data } = data; // 假设返回的数据结构为 { code, msg, data: newsList }
  if (code === 200) {
    // console.log('Success:', news_data);
    fetch(BASE_URL + 'news/pageViews', { // 增加浏览量
      method: 'POST',
      headers: {
          'Content-Type': 'application/json'
      },
      body: JSON.stringify({  // 修正1：用body代替data；修正2：对象转JSON字符串
        _id: id
      })
    })
    const res = news_data.find(item => item._id == id);
    // console.log(res)
    const text = textToHtmlParagraphs(res.desc)

     // const res = news_data.find(item => item.id == id);
    const next = news_data.find(item => item.id == id * 1 + 1);
    const pre = news_data.find(item => item.id == id * 1 - 1);
    // const text = textToHtmlParagraphs(res.content)
    let nextpage = ``
    // if(next) {
    //   nextpage = `<span class="d-next">下一篇</span><span class="d-next"><a  href="${location.href.replace(`id=${res.id}`,`id=${res.id * 1 + 1}`)}">${next.title}</a></span>`
    // } else {
    //   nextpage = `<span class="d-next">上一篇</span><span class="d-next"><a  href="${location.href.replace(`id=${res.id}`,`id=${res.id * 1 - 1}`)}">${pre.title}</a></span>`
    // }
    const year = new Date(res.updateTime).getFullYear();
    const month = new Date(res.updateTime).getMonth() + 1;
    const day = new Date(res.updateTime).getDate();
    const hour = new Date(res.updateTime).getHours();
    const minute = new Date(res.updateTime).getMinutes();
    const second = new Date(res.updateTime).getSeconds();
    const newsHtml  = `
    <div>
      <div class="d-title">${res.title_cn}</div>
      <div class="d-time flex ">
      <div>发表时间：${year}/${month}/${day} ${hour}:${minute}:${second}</div>
      <div style="margin-left: 20px;">浏览量: ${res.pageViews}</div>
       </div>
    </div>
    <article class="d-content" id="d-content">
    ${text}
    </article>
    <div class="d-small"><span>声明：此篇为集团原创文章，转载请标明出处链接：<a href="${location.href}">${location.href}</a></span></div>
    <div>
    ${nextpage}
    </div>
    `
    newsDetail.innerHTML += newsHtml;
    }
})

 
  

}

const detail = document.getElementById('detail');
const d1 = `
 <div class="detail">
     <img src="./imgs/sky.jpeg" alt="">
  </div>

  <div class="flex text-center btw detail-content">
    <div>
      <span>2465</span>
      <span>家 / 示例数据</span>
    </div>

    <div>
      <span>123</span>
      <span>种 / 示例数据</span>
    </div>

    <div>
      <span>4000</span>
      <span>+ / 示例数据</span>
    </div>

    <div>
      <span>98</span>
      <span>% / 示例数据</span>
    </div>
  </div>
`;

const d2 = `
<div class="flex btw">
    <div class="d2">
      <img src="./imgs/sky.jpeg" alt="">
      <div>行业研究</div>
      <span>专业提供柴油发电机组发电机设备生产</span>
    </div>

    <div class="d2">
      <img src="./imgs/sky.jpeg" alt="">
      <div>行业研究</div>
      <span>专业提供柴油发电机组发电机设备生产</span>
    </div>

    <div class="d2">
      <img src="./imgs/sky.jpeg" alt="">
      <div>行业研究</div>
      <span>专业提供柴油发电机组发电机设备生产</span>
    </div>

    <div class="d2">
      <img src="./imgs/sky.jpeg" alt="">
      <div>行业研究</div>
      <span>专业提供柴油发电机组发电机设备生产</span>
    </div>
  </div>

`;
const d3 = `
 <div class="d3 text-center">
    <div class="d3-title">核心优势</div>
    <div class="d3-tips">——  请输入要描述的内容进行内容补充  ——</div>
    <div class="flex">
      <img src="./imgs/2.jpg" alt="" srcset="" class="d3-img">
      <div>
        <div class="d3-bg">
          <img src="https://12794934.s61i.faiusr.com/4/AD0ItviMBhAEGAAgsdPplQYoxf-OKzBQOFA!60x60.png.webp" alt="">
          <div>提升效率</div>
          <div>请输入要描述的内容进行内容补充</div>
        </div>
        <div class="d3-bg">
          <img src="https://12794934.s61i.faiusr.com/4/AD0ItviMBhAEGAAgsdPplQYoxf-OKzBQOFA!60x60.png.webp" alt="">
          <div>提升效率</div>
          <div>请输入要描述的内容进行内容补充</div>
        </div>
        
        <div class="d3-bg">
          <img src="https://12794934.s61i.faiusr.com/4/AD0ItviMBhAEGAAgsdPplQYoxf-OKzBQOFA!60x60.png.webp" alt="">
          <div>提升效率</div>
          <div>请输入要描述的内容进行内容补充</div>
        </div>
        <div class="d3-bg">
          <img src="https://12794934.s61i.faiusr.com/4/AD0ItviMBhAEGAAgsdPplQYoxf-OKzBQOFA!60x60.png.webp" alt="">
          <div>提升效率</div>
          <div>请输入要描述的内容进行内容补充</div>
        </div>
      </div>
    </div>
  </div>
`;
if(detail) {
  const urlParams = new URLSearchParams(window.location.search);
  const id = urlParams.get('id');
  switch(id) {
    case '1':
      detail.innerHTML = d1
      break;
    case '2':
      detail.innerHTML = d2
      break;
    case '3':
      detail.innerHTML = d3
      break;
  }
}
const handleNavgation = (v) => {
  window.location.href = 'detail.html?id=' + v
}

// --- 表单提交 ---
const form = document.getElementById('form');
if(form) {
  form.addEventListener('submit', function(event) {
    event.preventDefault(); // 阻止表单默认提交行为
  
    var title_cn = document.querySelector('input[name="name"]').value;
    var phone = document.querySelector('input[name="phone"]').value;
    var mail = document.querySelector('input[name="mail"]').value;
    var remark = document.querySelector('textarea[name="remark"]')?.value || document.querySelector('textarea[name="remark2"]')?.value;
  
    // 清除之前的错误信息
    clearErrors();
  
    // 验证逻辑
    if (!title_cn) {
        showError('姓名', '姓名不能为空');
    } else if (!phone) {
        showError('电话', '电话不能为空');
    } else if (!mail) {
        showError('邮箱', '邮箱不能为空');
    } else if (!isValidEmail(mail)) {
        showError('邮箱', '邮箱格式不正确');
    } else if (!remark) {
        showError('留言', '留言不能为空');
    } else {
        // 如果所有验证都通过，则发送请求
        console.log(1111)
        submitForm(title_cn, phone, mail, remark);
    }
  });
}


function showError(field, message) {
  var errorElement = document.createElement('div');
  errorElement.className = 'error';
  errorElement.textContent = message;
  var label = document.querySelector(`label[for="${field}"]`);
  if (label) {
      label.parentNode.insertBefore(errorElement, label.nextSibling);
  }
}

function clearErrors() {
  var errors = document.querySelectorAll('.error');
  errors.forEach(function(error) {
      error.remove();
  });
}

function isValidEmail(email) {
  var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(String(email).toLowerCase());
}
function sbmit() {
  console.log(1111)
  var title_cn = document.querySelector('input[name="name"]').value;
  var phone = document.querySelector('input[name="phone"]').value;
  var mail = document.querySelector('input[name="mail"]').value;
  var remark = document.querySelector('textarea[name="remark"]')?.value || document.querySelector('textarea[name="remark2"]')?.value;

  // 清除之前的错误信息
  clearErrors();
  console.log(title_cn, phone, mail, remark)
  // 验证逻辑
  if (!title_cn) {
      showError('姓名', '姓名不能为空');
  } else if (!phone) {
      showError('电话', '电话不能为空');
  } else if (!mail) {
      showError('邮箱', '邮箱不能为空');
  } else if (!isValidEmail(mail)) {
      showError('邮箱', '邮箱格式不正确');
  } else if (!remark) {
      showError('留言', '留言不能为空');
  } else {
      // 如果所有验证都通过，则发送请求
      console.log(1111)
      submitForm(title_cn, phone, mail, remark);
  }

}

function submitForm() {
  var title_cn = document.querySelector('input[name="name"]').value;
  var phone = document.querySelector('input[name="phone"]').value;
  var mail = document.querySelector('input[name="mail"]').value;
  var remark = document.querySelector('textarea[name="remark"]')?.value || document.querySelector('textarea[name="remark2"]')?.value;
  console.log(title_cn, phone, mail, remark)
  if (!title_cn) {
    showError('姓名', '姓名不能为空');
    return
} else if (!phone) {
    showError('电话', '电话不能为空');
    return
  }
  fetch(BASE_URL + 'contacts/save', { // 这里替换为实际的API地址
      method: 'POST',
      headers: {
          'Content-Type': 'application/json'
      },
      body: JSON.stringify({ title_cn, phone, mail, remark })
  })
  .then(response => response.json())
  .then(data => {
    const { code, msg } = data;
    if (code === 200) {
      alert('提交成功！');
      console.log('Success:', data);
    } else {
      alert(msg);
    }
  })
  .catch((error) => {
      console.error('Error:', error);
  });
}


